const express = require('express');
const router = express.Router();
const ytdl = require('ytdl-core');
const fs = require('fs');
const puppeteer = require('puppeteer');
const { YOUTUBE_CLIENT_ID, YOUTUBE_CLIENT_SECRET } = require('../config');
const { google } = require('googleapis');
const OAuth2 = google.auth.OAuth2;
const { HttpsProxyAgent } = require('https-proxy-agent');  // 如果你使用的是 HTTPS 代理
const { spawn } = require('child_process');
const path = require('path');
const { Innertube  } = require('youtubei.js');

const REDIRECT_URI = 'https://localhost:8686/ytl/oauth2callback';

// Your OAuth 2.0 credentials
const CLIENT_ID = '698305732106-oc273ln8vg1m3hd3b6bmb80a6sqv2ntd.apps.googleusercontent.com';
const CLIENT_SECRET = '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';
const SCOPES = [
    'https://www.googleapis.com/auth/youtube.readonly'
];

// Create OAuth2 client
const oauth2Client = new OAuth2(
    CLIENT_ID,
    CLIENT_SECRET,
    REDIRECT_URI
);

const innertube = new Innertube({
    cookies: 'HSID=A0ZGz30sJo5lTTbdV; SSID=ALiFlZuPvx6sEQdDc; APISID=UdbUbLtvFG_lhNtb/AukaVa2ghv0utvg9L; SAPISID=qxJOD6iKB67P1Ohf/ATu02hDCd0NOw24qK; __Secure-1PAPISID=qxJOD6iKB67P1Ohf/ATu02hDCd0NOw24qK; __Secure-3PAPISID=qxJOD6iKB67P1Ohf/ATu02hDCd0NOw24qK; VISITOR_INFO1_LIVE=dJPQcImLJKU; VISITOR_PRIVACY_METADATA=CgJVUxIEGgAgTQ%3D%3D; PREF=f4=4000000&tz=Asia.Shanghai; SID=g.a000rQg-PlHXQTUKytHB4qtv7woM6MPOFcReDw0nc2TBPVNscNfXgtxzy9hSMkyrkwQ5Rz0J5QACgYKAX0SARASFQHGX2MiMq4VDWOPPcljM0AtGYLKUBoVAUF8yKp-otKeqsYJxBCyKmrCMA8H0076; __Secure-1PSID=g.a000rQg-PlHXQTUKytHB4qtv7woM6MPOFcReDw0nc2TBPVNscNfXdfQfMvdJ-Lws4niPpk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ZDI1cG5TbUVWNTI0MV9jbkFlQnZzOTVXM3Z1ejVoNFllbF9Fdy1ybmNXU19RUmVjaEJJQi1GeDVPZ1pmVXJVMm5VT1VFWExjNjlxZWpOZlRSZWU4VlpB; ST-3opvp5=session_logininfo=AFmmF2swRQIhAKEBvN2X0bjKgi_NtyI2_dcZcZKTRyWvE7RwEU816hp_AiBztH7HAdVRlrr2H5Wvp45jzPwyrBiv6fIq3aBNyCoklA%3AQUQ3MjNmd0hPNTNzQlg0dUxPbWc3QmVra0Jwa24xZTFpa3VVNzBLcmFndDJ0dkdKNzAxbFdqbUI2b0V1ZmhsbzRRcFVCLTlkYWVIZDI1cG5TbUVWNTI0MV9jbkFlQnZzOTVXM3Z1ejVoNFllbF9Fdy1ybmNXU19RUmVjaEJJQi1GeDVPZ1pmVXJVMm5VT1VFWExjNjlxZWpOZlRSZWU4VlpB; SIDCC=AKEyXzXYiMPONQnlfBTpWOQduNfyrdT9wKi2kZh6jOD_5f-LXp3gTzYzDuGsYSgafBBSaBzBzw; __Secure-1PSIDCC=AKEyXzU2ERW20vihLRHfavZlzl_CbzX52Nho60VwmTzZ4oqvpAwZA51Vb0zKuvCUg9OmR3Y0; __Secure-3PSIDCC=AKEyXzXlI6GFm3mqsnwtAIQqZkqC8RZrljHDDqEhLci8XG06CG6LIQ2cDl1FM3RCihTCPBLIHfs'
});

// Function to get authentication URL
function getAuthUrl() {
    return oauth2Client.generateAuthUrl({
        access_type: 'offline',
        scope: SCOPES,
        redirect_uri: REDIRECT_URI
    });
}

// Function to get tokens using the authorization code
async function getTokens(code) {
    try {
        const { tokens } = await oauth2Client.getToken({
            code,
            redirect_uri: REDIRECT_URI
        });
        console.log('tokes', tokens)
        oauth2Client.setCredentials(tokens);

        // Save tokens for future use
        fs.writeFileSync('tokens.json', JSON.stringify(tokens));
        return tokens;
    } catch (error) {
        console.error('Error getting tokens:', error);
        throw error;
    }
}

router.get('/google/auth', (req, res) => {
    // Redirect to Google's OAuth 2.0 authentication page
    const authUrl = getAuthUrl();
    res.redirect(authUrl);
});

router.get('/oauth2callback', async (req, res) => {
    try {
        const { code } = req.query;
        console.log('code:', code)
        await getTokens(code);
        res.send('Authentication successful! You can now download videos.');
    } catch (error) {
        res.status(500).send('Authentication failed: ' + error.message);
    }
});

// https://www.youtube.com/watch?v=WRFtrjAixvU
router.get('/download', async (req, res) => {
    const videoUrl = req.query.url; // 从查询参数获取视频链接
    const videoId = videoUrl.split('v=')[1];
    if (!videoUrl) {
        return res.status(400).send('视频 URL 是必需的');
    }

    // 设置下载视频的格式为 mp4
    const formatOption = 'mp4';

    try {
        // 指定下载路径
        const downloadPath = path.join('D:', 'Photo', 'video', 'test12201005.mp4');
        // const downloadPath = path.join(__dirname, '%(title)s.%(ext)s');
        const ytDlpPath = 'yt-dlp';
        const download = spawn(ytDlpPath, ['-f', formatOption, '-o', downloadPath, videoUrl]);

        // 设置响应头为流式传输，允许实时推送数据
        // res.setHeader('Content-Type', 'application/json');
        // res.write('Starting video download...\n');

        // 实时获取进度和输出并发送到客户端
        download.stdout.on('data', (data) => {
            // 发送进度信息或日志到客户端
            res.write(data.toString());
        });

        // 错误输出
        download.stderr.on('data', (data) => {
            // 发送错误信息到客户端
            res.write(`Error: ${data.toString()}`);
        });

        download.on('close', (code) => {
            if (code === 0) {
                // 假设下载的视频是 .mp4 格式
                res.download(downloadPath, (err) => {
                    if (err) {
                        console.log('err:', err)
                        res.status(500).send('Error downloading the video', err);
                    } else {
                        // 下载完成后，删除临时文件
                        fs.unlinkSync(downloadPath);
                    }
                });
                res.write('\nDownload completed successfully!');
            } else {
                res.status(500).send('Video download failed');
            }
        });
    } catch (error) {
        console.error(error);
        res.status(500).send('下载视频时发生错误');
    }
});



// 视频下载功能
router.get('/download2', async (req, res) => {
    const videoUrl = req.query.url;  // 获取查询参数中的 URL
    
    if (!videoUrl) {
        return res.status(400).send('Video URL is required.');
    }

    const videoId = videoUrl.split('v=')[1];

    try {
        const video = await innertube.getVideo(videoId); // 示例视频 ID
        console.log(video.title); // 获取视频标题

        // 获取第一个可用的下载链接
        const downloadLink = video.formats.find(format => format.mimeType.includes('video/mp4')).url;

        if (!downloadLink) {
            return res.status(404).send('Download link not found.');
        }

        // 设置下载文件的名字和格式
        const fileName = `${video.title}.mp4`.replace(/[\/:*?"<>|]/g, ''); // 去除非法字符

        // 下载视频并通过响应发送文件
        const response = await fetch(downloadLink);
        if (!response.ok) {
            return res.status(500).send('Failed to fetch video.');
        }

        res.setHeader('Content-Type', 'video/mp4');
        res.setHeader('Content-Disposition', `attachment; filename="${fileName}"`);
        
        // 将视频流通过响应发送
        response.body.pipe(res);

        // 监听流的完成
        response.body.on('end', () => {
            console.log(`Video ${fileName} has been sent.`);
        });

    } catch (error) {
        console.error('Error downloading video:', error);
        res.status(500).send('Internal Server Error');
    }
});

router.get('/download/shot', async (req, res) => {
    const webUrl = req.query.url; // 从查询参数获取视频链接
    if (!webUrl) {
        return res.status(400).send('URL 是必需的');
    }

    let browser;
    try {
        browser = await puppeteer.launch({
            headless: true, // 运行在无头模式（不显示浏览器窗口）
            args: ['--no-sandbox', '--disable-setuid-sandbox'] // 解决某些系统的权限问题
        });

        // 打开一个新页面
        const page = await browser.newPage();

        // 设置页面视口大小（例如 1920x1080）
        await page.setViewport({ width: 1920, height: 1080 });

        // 导航到目标网址
        await page.goto(webUrl, { waitUntil: 'networkidle2' }); // 等待页面加载完成

        // 模拟滚动页面，加载所有内容
        await autoScroll(page);

        // 截图并将其发送到响应
        const imageBuffer = await page.screenshot({ fullPage: true });

        fs.writeFileSync('screenshot-test.png', imageBuffer);

        // 设置响应头，返回 PNG 文件
        res.setHeader('Content-Type', 'image/png');
        res.setHeader('Content-Length', imageBuffer.length);
        res.end(imageBuffer);

    } catch (error) {
        console.error('截图失败：', error);
    } finally {
        // 关闭浏览器
        await browser.close();
    }
});

// 自动滚动函数
async function autoScroll(page) {
    await page.evaluate(async () => {
        await new Promise((resolve) => {
            let totalHeight = 0;
            const distance = 500; // 每次滚动的距离
            const timer = setInterval(() => {
                window.scrollBy(0, distance);
                totalHeight += distance;

                if (totalHeight >= document.body.scrollHeight) {
                    clearInterval(timer);
                    resolve();
                }
            }, 500); // 每 500 毫秒滚动一次
        });
    });
}

router.get('/generateCard', async (req, res) => {
    const url = req.query.url; // 从查询参数获取视频链接
    // 验证 Twitter 链接

    let browser;
    try {
        console.log('启动 Puppeteer...');
        browser = await puppeteer.launch({
            headless: true,
            args: ['--no-sandbox', '--disable-setuid-sandbox'],
        });

        const page = await browser.newPage();

        console.log('加载 Twitter 页面...');
        await page.goto(url, { waitUntil: 'networkidle2' });

        console.log('提取推文内容...');
        // 提取推文内容、用户名和图片
        const tweetData = await page.evaluate(() => {
            const textElement = document.querySelector('div[data-testid="tweetText"]');
            const usernameElement = document.querySelector('div[data-testid="User-Name"] a span');
            const imageElement = document.querySelector('div[data-testid="tweetPhoto"] img');

            return {
                text: textElement ? textElement.innerText : '无法获取推文内容',
                username: usernameElement ? usernameElement.innerText : '未知用户',
                imageUrl: imageElement ? imageElement.src : null,
            };
        });

        console.log('生成卡片 HTML...');
        const cardHtml = generateCardHtml(tweetData);

        console.log('渲染卡片为图片...');
        const imageBuffer = await renderCardToImage(browser, cardHtml);

        console.log('返回图片...');
        res.setHeader('Content-Type', 'image/png');
        res.end(imageBuffer);
    } catch (error) {
        console.error('生成卡片失败:', error);
        res.status(500).send('服务器错误，无法生成卡片。');
    } finally {
        if (browser) await browser.close();
    }
});

// 生成卡片 HTML
function generateCardHtml({ text, username, imageUrl }) {
    return `
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <style>
        body { font-family: Arial, sans-serif; margin: 0; padding: 0; background-color: #f5f8fa; }
        .card { width: 600px; border: 1px solid #e1e8ed; border-radius: 10px; background: #fff; box-shadow: 0 4px 6px rgba(0,0,0,0.1); padding: 20px; margin: 20px auto; }
        .username { font-weight: bold; color: #1da1f2; font-size: 20px; margin-bottom: 10px; }
        .text { margin: 10px 0; font-size: 18px; color: #14171a; }
        .media img { max-width: 100%; border-radius: 10px; margin-top: 10px; }
      </style>
    </head>
    <body>
      <div class="card">
        <div class="username">@${username}</div>
        <div class="text">${text}</div>
        ${imageUrl ? `<div class="media"><img src="${imageUrl}" alt="Tweet Media"></div>` : ''}
      </div>
    </body>
    </html>`;
}

// 使用 Puppeteer 渲染 HTML 并截屏
async function renderCardToImage(browser, html) {
    const page = await browser.newPage();
    await page.setContent(html, { waitUntil: 'networkidle0' });

    const imageBuffer = await page.screenshot({ fullPage: true });
    await page.close();

    return imageBuffer;
}

router.get('/downloadDouyin', async (req, res) => {
    const videoUrl = req.query.url; // 从查询参数获取抖音视频链接
    if (!videoUrl) {
        return res.status(400).send('视频 URL 是必需的');
    }

    let browser;
    try {
        browser = await puppeteer.launch({
            headless: true,
            args: ['--no-sandbox', '--disable-setuid-sandbox'],
        });

        const page = await browser.newPage();
        await page.goto(videoUrl, { waitUntil: 'networkidle2' });

        // 提取视频链接
        const videoSrc = await page.evaluate(() => {
            const videoElement = document.querySelector('video');
            return videoElement ? videoElement.src : null;
        });

        if (!videoSrc) {
            return res.status(404).send('无法找到视频');
        }

        // 下载视频
        const videoResponse = await page.goto(videoSrc);
        const videoBuffer = await videoResponse.buffer();

        // 设置响应头以提供下载
        res.setHeader('Content-Disposition', 'attachment; filename="douyin-video.mp4"');
        res.setHeader('Content-Type', 'video/mp4');
        res.end(videoBuffer);

    } catch (error) {
        console.error('下载抖音视频失败:', error);
        res.status(500).send('服务器错误，无法下载视频。');
    } finally {
        if (browser) await browser.close();
    }
});

module.exports = router;
